import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
// import 'package:flutter_baidu_mapapi_utils/flutter_baidu_mapapi_utils.dart';
// import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/domain/waystation/map_helper.dart';
import 'package:flutter_syt/domain/waystation/map_page.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/starter/i18n/localeization_processor.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/map_navigator_util.dart';
import 'package:flutter_syt/utils/utils_comment.dart';
import 'package:flutter_syt/widgets/normal_table.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '../../application.dart';
import 'way_station_input_bar.dart';

class SearchEntity {
  late String id;
  late String text;
  late double lat;
  late double lng;
  late String distance;
  late String address;
  late double disDouble;

  SearchEntity();
}

@RoutePage(name: "wayStationSearch")
class WayStationSearchPage extends StatefulWidget {
  double lat;
  double long;
  WayStationSearchPage(this.lat, this.long);
  @override
  State<StatefulWidget> createState() => _WayStationSearchPageState();
}

class _WayStationSearchPageState extends State<WayStationSearchPage>
    with AutomaticKeepAliveClientMixin {
  List<String> keywords = [];
  TextEditingController _searchController = TextEditingController();
  FocusNode _searchFocus = FocusNode();
  String _searchKey = "";
  NormalTableViewController _controller = NormalTableViewController();

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    if (widget.lat == 0.0) {
      // widget.lat = 39.917215;
      // widget.long = 116.380341;
      ///定位测试
      // LocationHelper.instance.result((LocationData event) async {
      //   // LocationHelper.stopLocation();
      //   // calculationDistance();
      //   if (mounted) {
      //     setState(() {
      //       widget.lat = event.location?.latitude ?? 0;
      //       widget.long = event.location?.longitude ?? 0;
      //       _controller.reloadData();
      //     });
      //   }
      // });
      // LocationHelper.instance.startLocation();
    }
    try {
      var keys = appContext.storage.getString("house_recent_search_keys") ?? "";
      keywords = json.decode(keys) as List<String>;
    } catch (e) {}
    _searchFocus.addListener(() {});
    _searchController.addListener(() {});
    super.initState();
  }

  onSearch() {
    _searchFocus.unfocus();
    keywords.remove(_searchKey);
    keywords.insert(0, _searchKey);
    if (keywords.length > 10) {
      keywords = keywords.sublist(0, 9);
    }
    var result = json.encoder.convert(keywords);
    appContext.storage.setString("house_recent_search_keys", result);
    _controller.reloadData();
  }

  Widget keywordsList() {
    List<Widget> children = keywords
        .map(
          (e) => GestureDetector(
            onTap: ClickUtils.debounce(() {
              _searchKey = e;
              _searchController.text = e;
              onSearch();
            }),
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(14)),
                border: Border.all(color: Color(0xff999999)),
                color: Colors.white,
              ),
              child: Text(
                e,
                style: TextStyle(
                  fontSize: 14,
                  color: Color(0xff666666),
                ),
              ),
            ),
          ),
        )
        .toList();
    return Column(
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          height: 50,
          alignment: Alignment.centerLeft,
          child: Text("最近搜索"),
        ),
        Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(
            horizontal: 16,
          ),
          child: Wrap(
            spacing: 10,
            runSpacing: 10,
            children: children,
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      // appBar: AppBar(
      //   iconTheme: IconThemeData(color: Colors.black),
      //   leading: GestureDetector(
      //     onTap: () async {
      //       _searchFocus.unfocus();
      //       await Future.delayed(Duration(seconds: 1));
      //       Navigator.pop(context);
      //     },
      //     child: Container(
      //       padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      //       child: Icon(
      //         Icons.arrow_back_ios_sharp,
      //         size: 16,
      //       ),
      //     ),
      //   ),
      //   centerTitle: true,
      //   backgroundColor: Colors.white,
      //   title: Text(
      //     S.of(context).Select_sites,
      //     style: TextStyle(
      //       fontSize: 18,
      //       color: Colors.black,
      //       fontStyle: FontStyle.normal,
      //     ),
      //   ),
      //   elevation: 1,
      // ),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        color: Colors.white,
        child: NormalTableView<SearchEntity>(
            controller: _controller,
            enableRefresh: false,
            enableLoadMore: false,
            header: (ctx) {
              return WayStationSearchBar(
                controller: _searchController,
                textfocus: _searchFocus,
                enableInput: true,
                searchCallback: (e) {
                  var tmp = e.trim();
                  _searchKey = tmp;
                  onSearch();
                },
              );
            },
            itemBuilder: (ctx, item) {
              var content = Container(
                color: Colors.white,
                padding: EdgeInsets.symmetric(vertical: 10),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Icon(Icons.location_on, color: const Color(0xFFF9DC54)),
                    Expanded(
                      child: Padding(
                        padding: EdgeInsets.only(left: 3),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              item.text,
                              style: TextStyle(
                                  fontSize: 16,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold),
                            ),
                            Padding(
                              padding: EdgeInsets.only(top: 6),
                              child: Text(
                                item.address,
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.black.withOpacity(0.6),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Text(
                      item.distance,
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.black.withOpacity(0.6),
                      ),
                    ),
                  ],
                ),
              );
              return GestureDetector(
                onTap: ClickUtils.debounce(() {
                  // Navigator.of(context).pop(MarkerEntity()
                  //   ..id = item.id
                  //   ..lat = item.lat
                  //   ..long = item.lng
                  //   ..name = item.text
                  //   ..address = item.address);
                  // MapNavigatorUtil.showBottom(context,
                  //     latitude: item.lat.toString(),
                  //     longitude: item.lng.toString());
                }),
                child: content,
              );
            },
            getData: (page) async {
              /*.create(e.id,e.name, e.address, "27km")).toList()*/;
              var list =
                  await API.shared.volunteer.houseList(search: _searchKey);
              List<SearchEntity> result = [];
              for (int i = 0; i < list.length; i++) {
                var e = list[i];
                double distance = 0;
                if (widget.lat != 0 || widget.long != 0) {
                  // var dis = UtilsComment.getDistance(
                  //     BMFCoordinate(e.lat, e.long),
                  //     BMFCoordinate(widget.lat, widget.long));
                  // dis = dis / 1000;
                  // distance = dis;
                }
                var entity = SearchEntity()
                  ..id = e.id
                  ..text = e.name
                  ..address = e.address
                  ..lat = e.lat
                  ..lng = e.long
                  ..distance =
                      "${distance == 0 ? "-" : distance.toStringAsFixed(2)}km"
                  ..disDouble = distance;
                result.add(entity);
              }
              result.sort((a, b) {
                return a.disDouble.compareTo(b.disDouble);
              });
              return result;
            }),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
